﻿using System.Data;
using System.Reflection;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxGridView.Rendering;
using DevExpress.Web.ASPxUploadControl;
using RR;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    const string UploadDirectory = "/dogovor/";
    protected RegistRar regrar = new RegistRar();
    string filePath = string.Empty;
    private int docID //код документа
    {
        get { return Convert.ToInt32(Request.QueryString["id"]); }
    } 


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack && !IsCallback)
        {
            // RefreshGrid(0, grd_Dog.ID);          
        }
        if (Session["DOGDOP"] != null)
        {
            grd_OrderDoc.DataSource = ds_OrderDoc;
            grd_OrderDoc.DataBind();
        }
    }

    protected void grd_dogdop_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        if (e.NewValues["CODE"] == null)
            e.NewValues["CODE"] = regrar.Gen_id("DOGDOP_gen");
        if (e.NewValues["DOG"] == null)
            e.NewValues["DOG"] = docID;
    }
    protected void grd_Dog_FocusedRowChanged(object sender, EventArgs e)
    {
        //Session["dogCode"] = Convert.ToInt32(grd_Dog.GetRowValues(grd_Dog.FocusedRowIndex, "CODE"));
    }
    protected void dogdop_pnl_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        if (e.Parameter != "null")
        {
            Session["dogCode"] = e.Parameter;
            grd_dogdop.DataBind();
        }
        else
        {
            Session["dogCode"] = 0;
            grd_dogdop.DataBind();
        }
    }
    protected void grd_dogdop_CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e)
    {
        string code = Convert.ToString(e.GetFieldValue("CODE"));
        if (e.Column.FieldName == "ORDERDOC")
        {
            // int code = Convert.ToInt32(grd_dogdop.GetRowValues(grd_dogdop.FocusedRowIndex, "CODE"));
            if (e.Value != "" && e.Value != null)
            {
                // e.DisplayText = String.Format("<a href='{0}'>скачать</a>", Convert.ToString(e.Value));
                e.DisplayText = String.Format("<a href='/doc/orderdoc.aspx?dcod={0}' style='color: #009900'>открыть</a>", Convert.ToString(e.Value));
            }
            else
            {
                //e.DisplayText = String.Format("<a href='dogdoc.aspx?dcod={0}' style='color: #0000FF'>создать</a>", code);
                e.DisplayText = string.Format("<a href='javascript:void(0);' onclick='CreateDoc({0})'  style='color: #0000FF'>создать</a>", code);
            }
        }
    }

    public string GetDisplayText(ASPxGridView grid, int row, string field)
    {
        GridViewDataColumn col = (GridViewDataColumn)grid.Columns[field];
        PropertyInfo pi = typeof(ASPxGridView).GetProperty("RenderHelper", BindingFlags.Instance | BindingFlags.NonPublic);
        ASPxGridViewRenderHelper renderHelper = (ASPxGridViewRenderHelper)pi.GetValue(grid, null);
        return renderHelper.TextBuilder.GetRowDisplayText(col, row);
    }

    private void createMoveDoc(string parameter)
    {
        int dopdog = Convert.ToInt32(parameter);
        //создаем заголовок внутреннего перемещения
        int code = 0;
        bool isNotRec = true;
        string kontr = DOG.FindByKey(regrar, docID).KONTRAGENT1.NAME;

        

        ORDERDOC doc = ORDERDOC.CreateORDERDOC(regrar);
        code = doc.CODE;
        //doc.DOCUMDATE = DateTime.Now;
        //doc.STATE = 0;   //не проводим документ
        //doc.DOGDOP = dopdog; //Ссылка на приложение к договору
        //doc.OPERATOR = Profile.UserInfo.ActiveWorker;
        //doc.WORKER = Profile.UserInfo.ActiveWorker;
        //doc.OPERTYPE = 0;       //Тип операции

        var query1 = (from d in regrar.DOGDOP
                      where d.CODE == dopdog
                      select d).First();
        DateTime dt = DateTime.Now;
        string note = string.Format("[авто]{0}, договор №{1}, доп. согл.№{2}", kontr, query1.DOG1.NOMDOG, query1.DOPNUM);
        regrar.MakeOrderDoc(dopdog, dt, Profile.UserInfo.ActiveWorker, Profile.UserInfo.ActiveWorker, note);
        //doc.NOTE = string.Format("[авто]{0}, договор №{1}, доп. согл.№{2}", kontr, query1.DOG1.NOMDOG, query1.DOPNUM);
        //regrar.SaveChanges();
        //создаем спецификацию внутреннего перемещения
        //var query = from d in regrar.DOGDOC
        //            where d.DOPDOG == dopdog
        //            select d;
        //int arcplace = new int();
        //foreach (var item in query)
        //{
        //    if (item.ARCPLACE != arcplace)
        //    {
        //        ORDERSPEC spec = ORDERSPEC.CreateORDERSPEC(regrar);
        //        spec.ORDERDOC = code;
        //        spec.ARCPLACE = Convert.ToInt32(item.ARCPLACE);
        //        isNotRec = false;
        //        arcplace = Convert.ToInt32(item.ARCPLACE);
        //    }
        //}
        //if (isNotRec)
        //    throw new Exception("Отсутствуют документы для перемещения!");
        ////regrar.SaveChanges();
        ////записываем код внетреннего перемещения в документ приложение к договору
        //var q = (from d in regrar.DOGDOP
        //         where d.CODE == dopdog
        //         select d).First();
        //q.ORDERDOC = code;
        
        //try
        //{
        //    regrar.SaveChanges();

        //}
        //catch (Exception ex)
        //{

        //    throw (ex.InnerException);
        //}
    }

    protected void clb1_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        //автосоздание внутреннего перемещения
        if (e.Parameter == string.Empty) { return; }

        createMoveDoc(e.Parameter);
        //
        grd_dogdop.DataBind();

    }
    protected void grd_dogdop_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
    {
        var state = grd_dogdop.GetRowValues(grd_dogdop.FocusedRowIndex, "ORDERDOC");
        if (state != null)
            throw new Exception("На основании документа создано вн.перемещение. Редактировать запрещено!");
    }
    protected void grd_dogdop_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
        var state = grd_dogdop.GetRowValues(grd_dogdop.FocusedRowIndex, "ORDERDOC");
        if (state != null)
            throw new Exception("На основании документа создано вн.перемещение. Удалять запрещено!");
    }

    protected void grd_OrderDoc_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        object masterKeyValue = grd_dogdop.GetRowValues(Convert.ToInt32(e.Parameters), "CODE");
        Session["DOGDOP"] = masterKeyValue;
        grd_OrderDoc.DataSource = ds_OrderDoc;
        grd_OrderDoc.PageIndex = 0;
        grd_OrderDoc.DataBind();
    }
    protected void grd_OrderDoc_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
        int state = Convert.ToInt32(grd_OrderDoc.GetRowValues(grd_OrderDoc.FocusedRowIndex, "STATE"));
        if (state == 1)
            throw new Exception("Документ проведен. Удалять запрещено!");
    }
    protected void grd_OrderDoc_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
    {
        int state = Convert.ToInt32(grd_OrderDoc.GetRowValues(grd_OrderDoc.FocusedRowIndex, "STATE"));
        if (state == 1)
            throw new Exception("Документ проведен. Редактировать запрещено!");
    }
    protected void grd_OrderDoc_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        if (e.NewValues["CODE"] == null)
            e.NewValues["CODE"] = regrar.Gen_id("ORDERDOC_gen");
        if (e.NewValues["STATE"] == null)
            e.NewValues["STATE"] = Convert.ToInt16(0);
        e.NewValues["OPERATOR"] = Profile.UserInfo.ActiveWorker;
    }
    protected void clb_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        int code = Convert.ToInt32(grd_OrderDoc.GetRowValues(grd_OrderDoc.FocusedRowIndex, "CODE"));
        CompleteDoc(code, Convert.ToInt16(e.Parameter));
    }
    protected void CompleteDoc(int code, Int16 complete)
    {
        try
        {
            var query = (from d in regrar.ORDERDOC
                         where d.CODE == code
                         select d).First();
            query.STATE = complete;
            regrar.SaveChanges();
        }
        catch (Exception ex)
        {
            throw ex.InnerException;
        }
    }
}